package com.qiantu.phone.widget;

import android.content.Context;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.lifecycle.LifecycleOwner;

import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControlDataFreshAirBean;
import com.qiantu.api.entity.DeviceModeValue;
import com.qiantu.api.entity.DeviceState;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.api.utils.DeviceInfoParseUtil;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.STATUS;


/**
 * Created by luzx on 2021/12/16.
 * 首页调光大view
 */


public class HomeFreshAirBigView extends HomeDeviceBaseView {

//    private TextView tvBigOffline;
    private TextView tvSpeedMode;
    private TextView tvClose;
    private StepView stepView;
    private ImageView imgDeviceFlag;
    private DeviceState mDeviceState;
    private DeviceState.StatusDTO mStatus;
    private List<DeviceModeValue> modeValueList;
    private List<DeviceModeValue> windspeed;
    private float minTemperature;
    private float maxTemperature;

    public HomeFreshAirBigView(Context context) {
        super(context, null);
    }

    public HomeFreshAirBigView(Context context, int type) {
        super(context, type);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_big_fresh_air_item;
    }

    protected void initView() {
        isBigView(true);
        super.initView();
        //bigView离线状态view重新赋值
//        tvBigOffline = findViewById(R.id.tv_offline_big);
        tvSpeedMode = findViewById(R.id.tv_speed_mode);
        tvClose = findViewById(R.id.tv_close);
        stepView = findViewById(R.id.step_view);
        imgDeviceFlag = findViewById(R.id.tv_out_device_flag);
        stepView.setStepChangeLister(new StepView.OnStepChangeListener() {
            @Override
            public void onStepChange(float step) {
                if (!mDevice.getIsOpen()) {
                    ToastUtils.show(R.string.device_off_disable);
                    return;
                }
                int speed = getWindSpeedValue((int)step);
//                Integer currentSpeed = mStatus.getWindspeed();
//                if(currentSpeed != speed){
//                    String speedModeName = getSpeedModeName(speed);
//                    tvSpeedMode.setText(speedModeName);
//                    windSpeedOperation(speed);
//                }
                String speedModeName = getSpeedModeName(speed);
                tvSpeedMode.setText(speedModeName);
                windSpeedOperation(speed);
            }
        });
    }

    private void setStatusBySwitch(boolean isOpen) {
        stepView.setEnabled(isOpen);
        if (isOpen) {
            tvClose.setVisibility(GONE);
            tvSpeedMode.setVisibility(VISIBLE);
        } else {
            tvClose.setVisibility(VISIBLE);
            tvSpeedMode.setVisibility(GONE);
        }
    }

    private String getSpeedModeName(Integer mode) {
        if(windspeed == null || windspeed.size() == 0){
            return null;
        }
        for (DeviceModeValue valueBean : windspeed) {
            if (valueBean.getValue() == mode) {
                int nameRes = getResources().getIdentifier(valueBean.getName(), "string", getContext().getPackageName());
                return getResources().getString(nameRes);
            }
        }
        return null;
    }

    private int getWindSpeedValue(Integer step){
        if(step == null){
            return 0;
        }
        for(int i=0; i<windspeed.size(); i++){
            if(i == step){
                return windspeed.get(i).getValue();
            }
        }
        return 0;
    }

    private int getWindSpeedStep(Integer value){
        if(value == null){
            return 0;
        }
        if(windspeed == null || windspeed.size() == 0){
            return 0;
        }
        for(int i=0; i<windspeed.size(); i++){
            if(windspeed.get(i).getValue() == value){
                return i;
            }
        }
        return 0;
    }

    //重载开关控制
    protected void switchOperation() {
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.POWER, mDevice.getIsOpen() ? 0 : 1);
//        option.put("temp", tvTemp.getText().toString());
        switchOperation(option);
    }

    @Override
    protected void onSwitchOperationSucceed(boolean isOpen) {
        setStatusBySwitch(isOpen);
        mDevice.setIsOpen(isOpen);
        LLDeviceDBManager.getInstance(getContext()).put(mDevice);
    }

    protected void updateView() {
        super.updateView();
        initConfigData();
        mDeviceState = mDevice.getStateData();
        mStatus = mDeviceState.getStatus();
//        if (mDevice.isIsOnline()) {
//            tvBigOffline.setVisibility(GONE);
//            tvSpeedMode.setVisibility(VISIBLE);
            String speedModeName = getSpeedModeName(mDevice.getWindSpeed());
            tvSpeedMode.setText(speedModeName);
            stepView.setStepNum(windspeed.size());
            stepView.setStep((float) getWindSpeedStep(mDevice.getWindSpeed()));
            setStatusBySwitch(mDevice.getIsOpen());
//        } else {
//            tvBigOffline.setVisibility(VISIBLE);
//            tvSpeedMode.setVisibility(GONE);
//        }
//        stepView.isOnline(mDevice.isIsOnline());
        imgDeviceFlag.setVisibility(mDevice.getIsFavourite() ? VISIBLE : INVISIBLE);
    }

    private void windSpeedOperation(int windspeed) {
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.WIND_SPEED, windspeed);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setWindSpeed(windspeed);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
            }

            @Override
            public void onFail(Exception e) {
                //取设备原来风速
                Integer speed = mStatus.getWindspeed();
                String speedModeName = getSpeedModeName(speed);
                tvSpeedMode.setText(speedModeName);
                stepView.setStep((float) getWindSpeedStep(speed));
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void initConfigData(){
        ControlDataFreshAirBean mFreshAirInfo = DeviceInfoParseUtil.parseData(getContext(), mDevice.getDeviceType(), ControlDataFreshAirBean.class);
        ControlDataFreshAirBean.ControlData controlData = mFreshAirInfo.getControlData();
        modeValueList = controlData.getMode();
        windspeed = controlData.getWindspeed();
        minTemperature = controlData.getTemperature_min();
        maxTemperature = controlData.getTemperature_max();
    }
}
